-module(parser_eng).
-include("protocol.hrl").
-behaviour(gen_server).
-export([init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).
-export([start/1,start_link/1]).
-define(SERVER,?MODULE).

start(Packet_Fun)  ->
	gen_server:start({local, Packet_Fun(get,protocol_id)}, ?MODULE, [Packet_Fun],[]).
	
start_link(Packet_Fun)  ->
	gen_server:start_link({local, Packet_Fun(get,protocol_id)}, ?MODULE, [Packet_Fun],[]).
	
init([Packet_Fun]) ->
	io:format("protocol ~s start...~n",[Packet_Fun(get,protocol_id)]),
	{ok,{runing,Packet_Fun,Packet_Fun(init,{})}}.
	
handle_call({packet_comming,Packet_Tuple},_,{running,Packet_Fun,State}) ->
	{reply,ok,{running,Packet_Fun,
		Packet_Fun(packet_comming,{Packet_Tuple,State})}};
		
handle_call(report,_,{EngSt,Packet_Fun,State}) ->
	{reply,Packet_Fun(report,State),{EngSt,Packet_Fun,State}};

handle_call(reset,_,{EngSt,Packet_Fun,State}) ->
	{reply,ok,{EngSt,Packet_Fun,Packet_Fun(reset,State)}};

handle_call(stop,_,{_,Packet_Fun,State}) ->
	{stop,caller_initiative,{stop,Packet_Fun,State}};

handle_call(_,_,State) ->
	{reply, {error,"no func define"}, State}.

handle_cast({packet_comming,Packet_Tuple},{runing,Packet_Fun,State}) ->
	{noreply,{runing,Packet_Fun,
		Packet_Fun(packet_comming,{Packet_Tuple,State})}};
	
handle_cast(_, State) ->
	{noreply,State}.

handle_info(_, State) ->
	{noreply,State}.
terminate(_, _) ->
	ok.
code_change(_, State, _) ->
	error_logger:info_msg("parser_eng reloaded ~n"),
	{ok,State}.	
		